$(function () {


    //总价固定
    var headrH = $("header").height();//整个头部的高度
    var cartH = $(".cart-process").height();//购物车图标的高度
    $(document).on("scroll", function () {
        var Dh = headrH + cartH - 20;
        var mH = $(this).scrollTop();
        if (mH <= Dh) {
            $(".pay-bar").addClass("z-bar-fixed");
        } else {
            $(".pay-bar").removeClass("z-bar-fixed");
        }
    })

    //渲染数据
    // <!-- 商品详情数量等 -->
    //发送ajax
    var total = 0;
    var num = 0;
    async function show() {
        var result = await $.get("../../api/getcarts", {
            uid: JSON.parse($.cookie("userinfo") || "{}").uId,
        })
        console.log(result)
        window.localStorage.setItem("shopcars", JSON.stringify(result))
        if (result.length != 0) {
            $(".cart-list").show();
            console.log(1111)
            $(".cart-empty").hide();
        } else {
            $(".cart-list").hide();
            console.log(22222)
            $(".cart-empty").show();
        }
        result.forEach(el => {
            var carHtml = ``;
            carHtml += `
            <tr class="item-entry">
            // <!-- 选择 -->
            <td class="cart-td-check">
                <input type="checkbox" checked="checked" class="j-goodscheck" data-pid=${el.pid} data-cid=${el.cId}>
            </td>
            // <!-- 商品名字和照片 -->
            <td class="goods-item-info clearFixed">
                <a href="javascript:;;" class="gsimages">
                    <img src="${el.pImg}" alt="商品相片">
                </a>
                <a href="javascript:;;" class="gstitle">
                    <span class="gstit-logo">
                        免税
                    </span>
                    <span class="gstit-text">${el.pName}</span>
                </a>
            </td>
            // <!-- 商品规格 -->
            <td class="cart-td-item-sku">
                <p class="Pcolor">${el.pSize}</p>
            </td>
            // <!-- 商品单价 -->
            <td class="cart-td-item-price">
                <p class="view-price">
                    ${el.pPrice}
                </p>
                <p class="discard">
                    ${el.pTotal}
                </p>
            </td>
            // <!-- 商品数量 -->
            <td class="cart-td-number">
                <div class="attr buy-num pure-form clearFixed">
                    <label>数量</label>
                    <div class="UpDownNum">
                        <button class="decrease sum"></button>
                        <input type="text" name="downInput" value=${el.pNum} class="inputNum">
                        <button class="increase sum">+</button>
                    </div>
                </div>
            </td>
            // <!-- 单品金额总计 -->
            <td class="cart-td-subtotal">
                <span class="view-subtotal">
                    ${el.pTotal}
                </span>
            </td>
            <td class="cart-td-delete">
                <a href="javascript:;;" class="btn-delete">删除</a>
            </td>
        </tr>
            `
            $(".v-carList").append(carHtml);
            num = $(".v-carList").children("tr").find(":checkbox:checked").length;
            //加减
        })
        //取出购物车对象,循环,计算总价
        let shopcarts = JSON.parse(window.localStorage.getItem("shopcars"));
        var shopcartsTotalPrice = 0;
        shopcarts.map((item) => {
            shopcartsTotalPrice += item.pNum * parseInt(item.pPrice)
        })
        $(".Allprice").text(shopcartsTotalPrice)
        $(".red").text(num)

        //复选框逻辑
        //全选反选
        $ckAll = $(".j-checkAll");//全选框
        $itemEntry = $(".item-entry");//商品信息的整行
        $ced = $itemEntry.find(":checkbox");//复选框
        //全选或反选
        $ckAll.on("change", function () {
            $ced = $itemEntry.find(":checkbox");
            if ($(this).prop("checked") === true) {
                $ced.prop("checked", true);
                let shopcars = JSON.parse(window.localStorage.getItem("shopcars"));
                let shopcartsTotalPrice = 0;
                shopcarts.map((item) => {
                    console.log(item)
                    shopcartsTotalPrice += item.pNum * parseInt(item.pPrice)
                })
                $(".Allprice").text(shopcartsTotalPrice)
            } else {
                $ced.prop("checked", false);
                $(".Allprice").text(0)
            }
        })
        //复选框决定全选框
        $ced.on("click", function () {
            //再次更新获取表格数据的checkbox
            $ced = $itemEntry.find(":checkbox");
            //判断打钩的盒子是否与全部盒子长度相等
            $itemEntry.find(":checkbox:checked").length === $ced.length ? $ckAll.prop("checked", true) : $ckAll.prop("checked", false)
            if($ced.prop("checked")==true){
                let shopcarts = JSON.parse(window.localStorage.getItem("shopcars"));
                // 先设总价为   
                let shopcartsTotalPrice = 0;
                //拿到当前点击的复选框的cid
                console.log(shopcarts)
            }
        })
    }
    show()

    //减数量
    var Gtotal = 0;
    $(".v-carList").on("click", ".decrease", function () {
        var num = $(this).next("input").val() - 1;
        if (num == 0) {
            return
        }
        $(this).next("input").val(num);
        //拿到当前商品的单价和数量获得单品总价
        let shopcarts = JSON.parse(window.localStorage.getItem("shopcars"));
        let cId = $(this).parents("tr").find(".j-goodscheck").data("cid");
        let shopcartsTotalPrice = 0;
        shopcarts.map((item) => {
            if (item.cId == cId) {
                item.pNum--;
            }
        })
        shopcarts.map((item) => {
            shopcartsTotalPrice += item.pNum * parseInt(item.pPrice)
        })
        $(".Allprice").text(shopcartsTotalPrice)
        window.localStorage.setItem("shopcars", JSON.stringify(shopcarts))

        var subtotal = $(this).parents("tr").find(".view-price").text() * num;
        //把值赋给单品总价文本

        goodnum = $(".v-carList").children("tr").find(":checkbox:checked").length
        //保存修改的数据,发送ajax与数据库同步
        var saveObj = {
            uid: JSON.parse($.cookie("userinfo") || "{}").uId,
            pid: $(this).parents("tr").find(".j-goodscheck").data("pid"),
            pNum: num,
            pSize: $(this).parents("tr").find(".Pcolor").text()
        }
        //发送ajax与数据库同步
        $.post({
            url: "../../api/modify",
            data: saveObj,
            dataType: "json",
        }).done((data) => {
            if (data.affectedRows >= 1) {
                console.log("修改入数据库成功")
            } else {
                console.log("修改入数据库失败")
            }
        })
    })
    
    //加数量
    $(".v-carList").on("click", ".increase", function () {
        var num = $(this).prev("input").val();
        num++;
        $(this).prev("input").val(num);
        let shopcarts = JSON.parse(window.localStorage.getItem("shopcars"));
        let cId = $(this).parents("tr").find(".j-goodscheck").data("cid");
        let shopcartsTotalPrice = 0;
        shopcarts.map((item) => {
            if (item.cId == cId) {
                item.pNum++;
            }
        })
        shopcarts.map((item) => {
            shopcartsTotalPrice += item.pNum * parseInt(item.pPrice)
        })
        $(".Allprice").text(shopcartsTotalPrice)
        window.localStorage.setItem("shopcars", JSON.stringify(shopcarts))

       //单品总价 
        var subtotal = $(this).parents("tr").find(".view-price").text() * num;
        //把单品总价渲染到页面上
        $(this).parents("tr").find($(".view-subtotal")).text(subtotal);
        // $(".Allprice").text(total);
        goodnum = $(".v-carList").children("tr").find(":checkbox:checked").length
        $(".red").text(goodnum)

        //保存修改的数据,发送ajax与数据库同步
        var saveObj = {
            uid: JSON.parse($.cookie("userinfo") || "{}").uId,
            pid: $(this).parents("tr").find(".j-goodscheck").data("pid"),
            pNum: num,
            pSize: $(this).parents("tr").find(".Pcolor").text()
        }
        //发送ajax与数据库同步
        $.post({
            url: "../../api/modify",
            data: saveObj,
            dataType: "json",
        }).done((data) => {
            if (data.affectedRows >= 1) {
                console.log("修改入数据库成功")
            } else {
                console.log("修改入数据库失败")
            }
        })
        console.log(saveObj)
    })

    //阻止表单默认提交行为
    $("form").on("submit", function () {
        return false
    })

    //删除数据
    $($(".v-carList")).on("click", ".btn-delete", function () {
        var delObj = {
            cid: $(this).parents("tr").find(".j-goodscheck").data("cid"),
            uid: JSON.parse($.cookie("userinfo") || "{}").uId,
            pid: $(this).parents("tr").find(".j-goodscheck").data("pid")
        }
        console.log(delObj)
        layer.confirm("删除我就真滴没辽,真滴要删除吗?", {
            btn: ["似的", "不辽"]
        },
            (index) => {
                layer.close(index);
                $(this).parents("tr").remove();
                $.ajax({
                    url: "../../api/delete",
                    type: "post",
                    data: delObj
                }).done((data) => {
                    console.log(data)
                    goodnum = $(".v-carList").children("tr").find(":checkbox:checked").length
                    $(".red").text(goodnum);
                    if (goodnum == 0) {
                        $(".cart-list").hide();
                        console.log(1111)
                        $(".cart-empty").show();
                    } else {
                        $(".cart-list").show();
                        console.log(22222)
                        $(".cart-empty").hide();
                    }
                })

            },
            (index) => {
                layer.close(index);
            }
        )
    })
    $(".c-999").on("click", function () {
        window.location.reload()
    })
})